﻿using UnityEngine;
using UnityEditor;

namespace HKTools
{
    /// <summary>
    /// HK_AreaTarget 的 Inspector 编辑器拓展
    /// </summary>
    [CanEditMultipleObjects]
    [CustomEditor(typeof(HK_AreaTarget))]
    public class HK_AreaTargetEditor : Editor
    {
        Transform camTemp_TF;

        public override void OnInspectorGUI()
        {
            GUILayout.Space(5);

            if (GUILayout.Button("根据物体名称，添加 Target 类型"))
            {
                HK_AddTargetEnumValue.AddTargetType((HK_BaseTarget)target);
            }

            GUILayout.Space(10);

            // 更新序列化对象  
            serializedObject.Update();

            EditorGUILayout.PropertyField(serializedObject.FindProperty("targetType"));
            EditorGUILayout.PropertyField(serializedObject.FindProperty("FOV"));

            EditorGUILayout.PropertyField(serializedObject.FindProperty("distance"));
            EditorGUILayout.PropertyField(serializedObject.FindProperty("areaWidth"));
            EditorGUILayout.PropertyField(serializedObject.FindProperty("areaLength"));

            // 应用修改  
            serializedObject.ApplyModifiedProperties();

            HK_AreaTarget targetItem = (HK_AreaTarget)target;

            if (targetItem.transform.localEulerAngles.y != 0)
            {
                if (Mathf.Abs(targetItem.transform.localEulerAngles.y) > 90)
                {
                    targetItem.transform.localEulerAngles = new Vector3(targetItem.transform.localEulerAngles.x, 180, 0);
                }
                else
                {
                    targetItem.transform.localEulerAngles = new Vector3(targetItem.transform.localEulerAngles.x, 0, 0);
                }
            }

            GUILayout.Space(10);

            if (GUILayout.Button("生成测试Camera"))
            {
                if (targetItem.transform.childCount > 0)
                    return;

                GameObject camTemp = new GameObject();
                camTemp.name = "Test Cam";
                camTemp.AddComponent<Camera>();

                camTemp_TF = camTemp.transform;
                camTemp_TF.SetParent(targetItem.transform);
                camTemp_TF.position = targetItem.transform.position + targetItem.transform.forward * targetItem.distance;
                camTemp_TF.LookAt(targetItem.transform);

                camTemp_TF.GetComponent<Camera>().fieldOfView = targetItem.FOV;
            }

            if (GUILayout.Button("删除测试Camera"))
            {
                if (targetItem.transform.childCount <= 0)
                    return;

                DestroyImmediate(targetItem.transform.GetComponentInChildren<Camera>().gameObject);
                camTemp_TF = null;
            }
        }
    }
}